home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: malloc question
- Date: 12 Mar 1996 18:48:31 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4i4gtv$fv3@sparcserver.lrz-muenchen.de>
- References: <4htonk$350@news.hklink.net> <4i492m$9jl@news1.warwick.net>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- acorn@warwick.net (Peter Kohlberger) writes:
- >alex@station.net (Alex Chu) wrote:
- >>Hi everybody,
-
- >>I have a question for the following snip C program.
- >>main()
- >>{
- >> PITEM head, current;
- >> head=(PITEM) malloc(sizeof(ITEM));
- >> ^^^^^^^
- >> head->val=1;
- >>}
-
- >>I want to know why need to use the type casting PITEM in front of the
- >>malloc ? Please help!
-
- >Basically, you need the cast because head is of type "pointer to ITEM"
- >and malloc returns type "pointer to void". If you try it without the
- >cast, your compiler will complain "cannot convert *void to *ITEM".
-
- Only if it is not a compiler for the language defined by ISO 9899,
- the document that defines the C programming language.
-
- [why is the automatic conversion from void pointer to any other
- pointer type not allowed in C? Well, it is allowed]
-
- >The answer is (mostly) so that the compiler can catch your errors.
- >While a pointer to void can be converted to a pointer to any type of
- >object, it's desirable to ensure that the conversion is the actual
- >intent of the programmer.
-
- >Consider the following:
-
- >typedef struct item1 {
- > int val;
- > struct item *next;
- >} ITEM1, *PITEM1;
-
- >typedef struct item2 {
- > int val;
- > struct item *next;
- > char text[40];
- >} ITEM2, *PITEM2;
-
- >main()
- >{
- > PITEM2 head2;
-
- > head2 =malloc(sizeof(ITEM1)); /* illegal */
-
- This is why it is good practice to write this as
-
- head2 = malloc(sizeof *head2);
-
- for thhose of us who are worried about "dereferencing an uninitialized
- pointer", rest assured. The argument of operator sizeof is _not_
- evaluated, but it's type is taken.
-
- > strcpy(head2->text,"Some text for here");
-
- Using head2 without checking the return value from malloc() was
- a bad idea since the 70s.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
- | ua302aa@sunmail.lrz-muenchen.de
-